package com.bbcare.followup.extend.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.*;
import com.bbcare.followup.extend.service.IExtendService;
import com.bbcare.followup.plat.controller.PatientController;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * 扩展接口控制器
 *
 * @author Ace
 */
@RestController
@RequestMapping("/service/")
public class ExtendController {

    private final Log logger = LogFactory.getLog(PatientController.class);

    @Autowired
    private IExtendService extendService;

    // 数据中心患者列表
    @PostMapping("/patient/queryPatientListDataCenter")
    public Map<String, Object> queryDataCenterPatientList(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in queryDataCenterPatientList----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id

        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);

        String phoneNo = jsonData.getString("phoneNum");
        String userName = jsonData.getString("patientName");// 可以是姓氏或姓名
        String status = jsonData.getString("status");
        String scaleAssessStatus = jsonData.getString("scaleAssessStatus");

        int page = jsonData.getIntValue("page");
        int rows = jsonData.getIntValue("rows");
        page = page == 0 ? 1 : page;
        rows = rows == 0 ? 10 : rows;

        if (null != status && !"".equals(status)) {
            paramMap.put("status", status);
        }
        if (null != phoneNo && !"".equals(phoneNo)) {
            paramMap.put("phoneNo", phoneNo);
        }
        if (null != userName && !"".equals(userName)) {
            paramMap.put("userName", userName);
        }

        int start = (page - 1) * rows;
        int end = start + rows - 1;
        paramMap.put("start", start);
        paramMap.put("end", end);

        // 增加队列id和患者来源
        paramMap.put("queueId", jsonData.getString("queueId"));
        paramMap.put("sourceType", jsonData.getString("opType"));
        // paramMap.put("premature", jsonData.getString("premature"));

        Integer ageTo = jsonData.getInteger("ageTo");
        Integer ageFrom = jsonData.getInteger("ageFrom");

        Calendar to = Calendar.getInstance();
        if (ageTo != null) {
            to.add(Calendar.MONTH, -ageTo);
            paramMap.put("ageTo", DateUtil.getDate_8(to.getTime()));
        }

        Calendar from = Calendar.getInstance();
        if (ageFrom != null) {
            from.add(Calendar.MONTH, -ageFrom);
            // from.set(Calendar.DAY_OF_MONTH,
            // from.getActualMaximum(Calendar.DAY_OF_MONTH));
            paramMap.put("ageFrom", DateUtil.getDate_8(from.getTime()));
        }

        if (!StringUtils.isEmpty(jsonData.getString("hisNo"))) {
            paramMap.put("hisNo", jsonData.getString("hisNo"));
        }
        // 可以查询队列中正常状态患者，也可查询扫码建档待审核状态的患者
        String confirmFlag = jsonData.getString("confirmFlag");
        if (StringUtils.isNotEmpty(confirmFlag)) {
            paramMap.put("confirmFlag", confirmFlag);
        }
        paramMap.put("taskAuditStatus", jsonData.getString("taskAuditStatus"));

        // 针对Datatable特殊处理
        String jsonStr = jsonData.getString(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonStr)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonStr);
            draw = jsonTable.getIntValue("draw");
            paramMap.put("start", jsonTable.getIntValue("start"));
            paramMap.put("end", jsonTable.getIntValue("length"));
        }

        if (StringUtils.isNotEmpty(scaleAssessStatus)){
            paramMap.put("scaleAssessStatus",scaleAssessStatus);
        }

        Map<String, Object> retMap = extendService.queryDataCenterPatientList(paramMap);
        // 针对Datatable特殊处理
        if (!StringUtils.isEmpty(jsonStr)) {
            retMap.put("draw", draw);
            retMap.put("recordsTotal", retMap.get("total"));
            retMap.put("recordsFiltered", retMap.get("total"));
        }
        return retMap;
    }

    // 该接口暂时停用
    @PostMapping("/getReadWriteRole")
    public ResultModel<Object> getReadWriteRole(@RequestBody String args) throws Exception {
        logger.warn("getReadWriteRole() ======== args : " + args);
        Map<String, Object> role = extendService.getReadWriteRole(args);
        return new ResultModel<>(role);
    }
}
